package me.pplay.playtalk.activity;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import me.pplay.playtalk.ApplicationTrans;
import me.pplay.playtalk.R;
import me.pplay.playtalk.adapter.ChatConversationAdapter;
import me.pplay.playtalk.adapter.ConversationFriendAdapter;
import me.pplay.playtalk.bean.Chat;
import me.pplay.playtalk.bean.ChattingRecord;
import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.database.ChatListDb;
import me.pplay.playtalk.net.ConnectivityManagerUtil;
import me.pplay.playtalk.protocol.DataCallBack;
import me.pplay.playtalk.protocol.TpChat;
import me.pplay.playtalk.protocol.TpChatRoom;
import me.pplay.playtalk.protocol.TpFile;
import me.pplay.playtalk.protocol.bean.RspData;
import me.pplay.playtalk.protocol.bean.TPBuddyinfo;
import me.pplay.playtalk.protocol.bean.TpFileData;
import me.pplay.playtalk.protocol.bean.TpGroup;
import me.pplay.playtalk.service.PlayTalkService;
import me.pplay.playtalk.util.AsyncImageLoader;
import me.pplay.playtalk.util.BuddyInfoUtil;
import me.pplay.playtalk.util.LogManager;
import me.pplay.playtalk.util.fileUtil.ChattingRecordFile;
import me.pplay.playtalk.util.fileUtil.FileUtil;
import me.pplay.playtalk.util.fileUtil.MediaFile;
import me.pplay.playtalk.view.AudioShowDialog;
import me.pplay.playtalk.view.DialogMenu;
import me.pplay.playtalk.view.SmileyLayout;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import dalvik.system.VMRuntime;

public class ChatConversationActivity extends BaseActivity implements OnClickListener {

	private Thread notificationThread;
	private final int notificatoinDur = 1000;
	private boolean isActiveThread 	= false;
	private boolean isClickOk		= false;
	private int notificationCount 	= 0;
	private int sdkVersion			= -1;
	private int clickPosition 		= 0;
	private String notificationValue;
	private DialogMenu sendFilesDialog, chattingItemDialog;
	private AudioShowDialog audioShowDialog;
	private InputMethodManager inputManager;
	private ClipboardManager clip;
	private TpChatRoom tpChatRoom;
	private TpChat tpChat;
	private ProgressDialog progressDialog;

	// View declare
	private ListView listView, searchListView;
	private EditText editText_msg, searchTv;
	private TextView userName_tv, notification_tv;
	private RelativeLayout layout_sendmsg, layout_audio, layout_bar, layout_search;
	private ImageButton btn_back, btn_viewDetail, btn_sendfiles, btn_smiley,  btn_cancel_audio;
	private LinearLayout smiley_layout, notification_layout, layout_cancel, layout_ok, layout_bar_search,layout_r1;
	private SmileyLayout smiley;
	private Button btn_sendmsg, btn_audio_talk;

	// Data declare
	private String strImgPath				= "";
	private final int TAKEPHOTO 			= 1;// 拍照
	private final int CHOOSE_PHOTO 			= 2; // 选择照片
	private final int TAKEVIDEO 			= 3;// 拍视频
	private final int CHOOSE_VIDEO 			= 4; // 选择视频
	private final String IMAGE_UNSPECIFIED 	= "image/*";
	private final String VIDEO_UNSPECIFIED 	= "video/*";
	public 	static final int SETADAPTER 	= 1;
	private final int GETCHATTINGRECORD 	= 2;
	private final int SETADAPTER_TOP 		= 3;
	public 	static final int SMILEY_TEXT 	= 4;
	private final int DISPLAYNOTIFICATION 	= 5;
	private final int HIDENOTIFICATION 		= 6;
	private final int SEARCH_SETADAPTER		= 7;
	private final int ENABLED_OK 			= 8;
	private final int GROUP_CREATE 			= 9;

	private List<ChattingRecord> chatList;
	private ChatConversationAdapter adapter;
	private ConversationFriendAdapter searchAdapter;
	private AsyncImageLoader imageLoader;
	private List<TPBuddyinfo> fList;
	private List<TPBuddyinfo> searchList;
	/**
	 * 点对点消息
	 */
	private int skyId;
	private String skyName;
//	private String icon;
	private int chat_type = -1; // 0 点对点， 5： 群会话

	// community
	private TpGroup tpGroup;

	private String from = "";

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case GETCHATTINGRECORD:
				initGetChattingRecordList();
				break;
			case Globals.SETADAPTER:
				ChattingRecord cr = (ChattingRecord) msg.getData().getSerializable("obj");
				if (cr == null)
					return;
				chatList.add(cr);
				handler.sendEmptyMessage(SETADAPTER);
			case SETADAPTER:
				if (adapter == null) {
					adapter = new ChatConversationAdapter(ChatConversationActivity.this, chatList, imageLoader, sdkVersion, handler);
					listView.setAdapter(adapter);
				} else {
					adapter.notifyDataSetChanged();
				}
				handler.sendEmptyMessage(SETADAPTER_TOP);
				break;
			case SETADAPTER_TOP:
				if (chatList != null)
					listView.setSelection(chatList.size());
				break;
			case SMILEY_TEXT:
				String stickerPath = (String) msg.obj;
				if(msg.arg1 < 2)
					appendTopic(stickerPath);
				else
					sendSticker(stickerPath);
				// smiley_layout.setVisibility(View.GONE);
				break;
			case DISPLAYNOTIFICATION:
				dispalynotifacation();
				break;
			case HIDENOTIFICATION:
				hideNotificatoin();
				break;
			case SEARCH_SETADAPTER:
				if (searchAdapter == null) {
					searchAdapter = new ConversationFriendAdapter(ChatConversationActivity.this, searchList, imageLoader, handler);
					searchListView.setAdapter(searchAdapter);
				} else {
					searchAdapter.notifyDataSetChanged();
				}
				break;
			case 11:
				showToast(getString(R.string.more_group));
				break;
			case ENABLED_OK:
				layout_ok.setEnabled(searchAdapter.selectedList.size()> 0);
				break;
			case GROUP_CREATE:

				break;
			case TpChat.CHAT_CREATECONFERENCE_OK:
				layout_r1.setVisibility(View.VISIBLE);
				skyId 	= tpGroup.getId();
//				icon 	= null;
				userName_tv.setText(tpGroup.getName());
				PlayTalkService.getInstance().setValues(tpGroup, skyId);
				break;
			case Globals.SETTING_NEW_CONFERENCE_NAME:
				skyName = (String)msg.getData().getSerializable("obj");
				userName_tv.setText(skyName);
			case TpChat.CHAT_CREATECONFERENCE_ERR:
			case TpChat.CHAT_CONFERENCE_CREATE_TIMEOUT:
				showToast(getString(R.string.net_timeout));
				break;
			case TpChat.CHAT_GETCONFERENCEBUDDIES_OK:{
				progressDialog.dismiss();
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putInt("type", ChatViewMemberActivity.GROUP_TYPE);
				bundle.putInt("id", skyId);
				intent.putExtras(bundle);
				intent.setClass(ChatConversationActivity.this, ChatViewMemberActivity.class);
				startActivity(intent);
				break;
			}
			case TpChat.CHAT_GETCONFERENCEBUDDIES_ERR:
				progressDialog.dismiss();
				RspData rspdata = (RspData) msg.obj;
				showToast(rspdata.getString() == null ? "Unkown err" : rspdata.getString());
				break;
			case TpChat.CHAT_GETCONFERENCEBUDDIES_TIMEOUT:
				progressDialog.dismiss();
				showToast("Time out");
				break;
			case TpChatRoom.CHATROOM_BUDDY_OK:{
				progressDialog.dismiss();
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putInt("type", ChatViewMemberActivity.COMMUNITY_TYPE);
				intent.putExtras(bundle);
				intent.setClass(ChatConversationActivity.this, ChatViewMemberActivity.class);
				startActivity(intent);
				break;
			}
			case TpChatRoom.CHATROOM_BUDDY_ERR:
				progressDialog.dismiss();
				RspData data = (RspData) msg.obj;
				showToast(data.getString() == null ? "Unkown err" : data.getString());
				break;
			case TpChatRoom.CHATROOM_BUDDY_TIMEOUT:
				progressDialog.dismiss();
				showToast("Time out");
				break;
			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_chat_conversation);
		VMRuntime.getRuntime().setMinimumHeapSize(8 * 1024 * 1024);
		VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
		findViews();
		initDatas();
		clickEvents();
	}

	/**
	 * Get View by viewId
	 */
	private void findViews() {
		listView 			= (ListView) findViewById(R.id.listView);
		editText_msg 		= (EditText) findViewById(R.id.editText_msg);
		userName_tv 		= (TextView) findViewById(R.id.userName_tv);
//		audio_talk_tv 		= (TextView) findViewById(R.id.audio_talk_tv);
		layout_sendmsg		= (RelativeLayout) findViewById(R.id.layout_sendmsg);
		layout_audio 		= (RelativeLayout) findViewById(R.id.layout_audio);
		btn_back 			= (ImageButton) findViewById(R.id.btn_back);
		btn_viewDetail 		= (ImageButton) findViewById(R.id.btn_viewDetail);
		btn_sendfiles 		= (ImageButton) findViewById(R.id.btn_sendfiles);
		btn_smiley 			= (ImageButton) findViewById(R.id.btn_smiley);
		btn_sendmsg 		= (Button) findViewById(R.id.btn_sendmsg);
		btn_cancel_audio 	= (ImageButton) findViewById(R.id.btn_cancel_audio);
		btn_audio_talk	 	= (Button) findViewById(R.id.btn_audio_talk);
		smiley_layout 		= (LinearLayout) findViewById(R.id.smiley_layout);
		// smiley = (SmileyLayout)findViewById(R.id.smiley);
		notification_tv 	= (TextView) findViewById(R.id.notification_tv);
		notification_layout = (LinearLayout) findViewById(R.id.notification_layout);

		layout_search 		= (RelativeLayout) findViewById(R.id.layout_search);
		searchListView 		= (ListView) findViewById(R.id.searchListView);
		searchTv 			= (EditText) findViewById(R.id.searchTv);
		layout_cancel 		= (LinearLayout) findViewById(R.id.layout_cancel);
		layout_ok 			= (LinearLayout) findViewById(R.id.layout_ok);
		layout_bar_search 	= (LinearLayout) findViewById(R.id.layout_bar_search);
		layout_bar 			= (RelativeLayout) findViewById(R.id.layout_bar);
		layout_r1			= (LinearLayout) findViewById(R.id.layout_r1);
	}

	/**
	 * init Datas
	 */
	private void initDatas() {
		initNotificationThread();
		sdkVersion					= Build.VERSION.SDK_INT;
		inputManager 				= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		chatList 					= new ArrayList<ChattingRecord>();
		imageLoader 				= new AsyncImageLoader();
		ApplicationTrans appState 	= (ApplicationTrans) getApplicationContext();
		tpChat 						= appState.getTpChat();

		Bundle bundle = getIntent().getExtras();
		from = bundle.getString("from");

		if (from.equals("community")) {
			tpGroup 		= (TpGroup) bundle.getSerializable("tpgroup");
			userName_tv.setText(tpGroup.getName());
			btn_sendfiles.setVisibility(View.GONE);
			tpChatRoom 		= appState.getTpChatRoom();
		} else if (from.equals("tpbuddyinfo")) {
			skyId 			= bundle.getInt("skyid", -1);
			skyName 		= bundle.getString("skyname");
//			icon 			= bundle.getString("icon");
			chat_type 		= bundle.getInt("chat_type", 0);
			userName_tv.setText(skyName);
			handler.sendEmptyMessage(GETCHATTINGRECORD);
		} else if (from.equals("newConversation")) { // 创建新的会话
			layout_r1.setVisibility(View.GONE);
			userName_tv.setText(getString(R.string.create_new_message));
			btn_viewDetail.setEnabled(false);
			layout_search.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
			layout_bar.setVisibility(View.GONE);
			layout_bar_search.setVisibility(View.VISIBLE);
			searchTv.addTextChangedListener(new MyTextWatcher());
			searchList 		= new ArrayList<TPBuddyinfo>();
			layout_ok.setEnabled(false);
			fList 			= tpChat.tp_chat_getfriendslist();
			if (fList == null)
				return;
			for (int i = 0; i < fList.size(); i++) {
				searchList.add(fList.get(i));
			}
			handler.sendEmptyMessage(SEARCH_SETADAPTER);
		}
	}

	// 读取后10条记录
	private void initGetChattingRecordList() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				LogManager.LogShow("ChatConversationActivity", "chartRecordList : skyId:" + skyId);
				chatList = ChattingRecordFile.getChattingRecordByFile(skyId, 10);
				handler.sendEmptyMessage(SETADAPTER);
			}
		}).start();
	}

	private void clickEvents() {
		btn_back.setOnClickListener(this);
		btn_viewDetail.setOnClickListener(this);
		btn_sendfiles.setOnClickListener(this);
		btn_smiley.setOnClickListener(this);
		btn_sendmsg.setOnClickListener(this);
		btn_cancel_audio.setOnClickListener(this);
		editText_msg.setOnClickListener(this);
		layout_cancel.setOnClickListener(this);
		layout_ok.setOnClickListener(this);
		btn_audio_talk.setOnTouchListener(new AudioOnTouchListener());
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				clickPosition = arg2;
				if (chattingItemDialog == null) {
					String title = "";
					String[]  titles = new String[]{};
					if (from.equals("community")) {
						title 	= tpGroup.getName();
						titles  = getResources().getStringArray(R.array.array_community_menu);
					} else/* if (from.equals("tpbuddyinfo")) */{
						title 	= getString(R.string.dialog_chattingitem);
						titles  = getResources().getStringArray(R.array.array_viewdetail_menu);
					}
					if(title.equals(""))
						return false;
					chattingItemDialog = new DialogMenu(ChatConversationActivity.this, ChatConversationActivity.this.findViewById(R.id.rootView), 
							R.drawable.dialog_icon, title, new int[]{R.drawable.dialog_copy, R.drawable.dialog_view_details_icon}, titles, new DataCallBack(){

						@Override
						public void Callback(int result, RspData resultdata, Object obj) {
							chattingItemDialog.show(false);
							ChattingRecord cr = chatList.get(clickPosition);
							if (cr == null)
								return;
							if (result == 0) { // copy chat
								if (clip == null)
									clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
								clip.setText(cr.content);
							} else {// 详细信息
								Intent intent = new Intent();
								intent.putExtra("skyid", cr.skyid);
								intent.setClass(ChatConversationActivity.this, ContactDetailsAboutActivity.class);
								startActivity(intent);
							}
						}
						
					});
				}
				chattingItemDialog.show(true);
				return false;
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			goBack();
			ChatConversationActivity.this.finish();
			break;
		case R.id.btn_viewDetail:
			viewDetailSetting();
			break;
		case R.id.btn_sendfiles:
			showSendFilesMenu();
			break;
		case R.id.btn_smiley:
			showSmiley();
			break;
		case R.id.btn_sendmsg:
			sendMsg("0", editText_msg.getText().toString());
			editText_msg.setText("");
			break;
		case R.id.btn_cancel_audio:
			layout_audio.setVisibility(View.GONE);
			layout_sendmsg.setVisibility(View.VISIBLE);
			break;
		case R.id.editText_msg:
			smiley_layout.setVisibility(View.GONE);
			break;
		case R.id.layout_cancel:
			hideSearchLayout();
			ChatConversationActivity.this.finish();
			break;
		case R.id.layout_ok:
			if (!ConnectivityManagerUtil.isAccessNetwork(this)) {
				showToast(getString(R.string.noNet));
				return;
			}
			if(!isClickOk){
				isClickOk = true;
				String text = "";
				int countS = searchAdapter.selectedList.size();
				for (int i = 0; i < countS ; i++) {
					text += BuddyInfoUtil.getAlias(searchAdapter.selectedList.get(i));
					if (countS - 1 != i)
						text += ",";
				}
				searchTv.setText(text);
				searchTv.setEnabled(false);
			}else{
				hideSearchLayout();
				layout_ok();
			}
			searchListView.setVisibility(View.GONE);
			break;
		default:
			break;
		}
	}

	/*********************** very imagebutton onclick event handle start *********************************/
	private void viewDetailSetting() { // setting
		if(from.equals("community")){
			LogManager.LogShow("ChatConversationActivity", "from:" + from + "tp_chatroom_get_friends:");
			progressDialog = ProgressDialog.show(ChatConversationActivity.this, getString(R.string.loading), getString(R.string.waittng), true, false); 
			progressDialog.show();
			tpChatRoom.tp_chatroom_get_friends(tpGroup.getId(), tpGroup.getCurrentsize(), tpGroup.getTotalsize(), new DataCallBack() {

				@Override
				public void Callback(int result, RspData resultdata, Object obj) {
					// TODO Auto-generated method stub
					LogManager.LogShow("ChatConversationActivity", "tp_chatroom_get_friends  Callback result= " + result);
					handler.sendEmptyMessage(result);
				}
			});
		}else{
			if(0 == chat_type){//p2p
				LogManager.LogShow("ChatConversationActivity", "chat_type:" + chat_type);
				TPBuddyinfo tpBuddyinfo = new TPBuddyinfo();
				Bundle data = getIntent().getExtras();
				tpBuddyinfo.setSkyid(data.getInt("skyid", -1));
				tpBuddyinfo.setName(data.getString("skyname"));
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putInt("type", ChatViewMemberActivity.P2P_TYPE);
				bundle.putSerializable("member", (TPBuddyinfo)tpBuddyinfo);
				intent.putExtras(bundle);
				intent.setClass(ChatConversationActivity.this, ChatViewMemberActivity.class);
				startActivity(intent);
			}else if(5 == chat_type){//group
				LogManager.LogShow("ChatConversationActivity", "chat_type:" + chat_type);
				progressDialog = ProgressDialog.show(ChatConversationActivity.this, getString(R.string.loading), getString(R.string.waittng), true, false); 
				progressDialog.show();
				TpGroup group = tpChat.tp_chat_getConferencebyid(skyId);
				if(null != group){
					tpChat.tp_conference_get_buddies(group.getId(), group.getCurrentsize(), group.getTotalsize(), new DataCallBack() {
	
						@Override
						public void Callback(int result, RspData resultdata, Object obj) {
							// TODO Auto-generated method stub
							LogManager.LogShow("ChatConversationActivity", "tp_conference_get_buddies  Callback result= " + result);
							handler.sendEmptyMessage(result);
						}
					});
				}
			}
		}
	}

	private void showSendFilesMenu() {
		if (sendFilesDialog == null) {
				sendFilesDialog = new DialogMenu(ChatConversationActivity.this, ChatConversationActivity.this.findViewById(R.id.rootView), 
						R.drawable.attachment, getString(R.string.dialog_attach), new int[]{R.drawable.dialog_take_photo, R.drawable.dialog_choose_photo, R.drawable.dialog_take_video, R.drawable.dialog_choose_video,R.drawable.dialog_audio},
						getResources().getStringArray(R.array.array_sendfiles_menu), new DataCallBack(){
					@Override
					public void Callback(int result, RspData resultdata, Object obj) {
						if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
							switch (result) {
							case 0:
								cameraMethod();
								break;
							case 1:
								Intent intent 		= new Intent(Intent.ACTION_GET_CONTENT, null);
								intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
								startActivityForResult(intent, CHOOSE_PHOTO);
								break;
							case 2:
								videoMethod();
								break;
							case 3:
								Intent innerIntent 	= new Intent(Intent.ACTION_GET_CONTENT);
								innerIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, VIDEO_UNSPECIFIED);
								startActivityForResult(innerIntent, CHOOSE_VIDEO);
								break;
							case 4:
								inputManager.hideSoftInputFromWindow(editText_msg.getWindowToken(), 0);
								layout_audio.setVisibility(View.VISIBLE);
								layout_sendmsg.setVisibility(View.GONE);
								break;
							}
						}
						sendFilesDialog.show(false);
					}
			});
		}
		sendFilesDialog.show(true);
	}

	private void showSmiley() {
		if (smiley == null) {
			smiley = new SmileyLayout(this.getApplicationContext(), handler);
			smiley_layout.addView(smiley);
		}
		if (smiley_layout.getVisibility() == View.GONE)
			smiley_layout.setVisibility(View.VISIBLE);
		else
			smiley_layout.setVisibility(View.GONE);
		inputManager.hideSoftInputFromWindow(editText_msg.getWindowToken(), 0);
	}
	
	private void sendSticker(String stickerPath){
		if(stickerPath == null || stickerPath.equals(""))
			return;
		
	}

	/**
	 * @param type
	 *            类型
	 * @param msg
	 *            消息内容（多媒体以URL形式）
	 * @param index
	 *            谁发的
	 */
	private void sendMsg(String type, String msg) { // 发消息
		if (msg == null)
			return;
		if (msg.trim().equals("")) {
			showToast(getString(R.string.send_msg_null));
			return;
		}
		if (!ConnectivityManagerUtil.isAccessNetwork(this)) {
			showToast(getString(R.string.noNet));
			return;
		}
		String alias		= BuddyInfoUtil.getAlias(Globals.myInfo);
		ChattingRecord chat = new ChattingRecord(Globals.skyid, alias, null, type, msg, System.currentTimeMillis() + "");
		chatList.add(chat);
		handler.sendEmptyMessage(SETADAPTER);
		LogManager.LogShow("ChatConversationActivity", "from:" + from + " send msg start:" + msg + " skyId: "+skyId + "  chat_type:"+ chat_type, LogManager.INFO);
		if (from.equals("community")) {
			try {
				tpChatRoom.tp_chatroom_send_im( new String(alias.getBytes("UTF-8")), tpGroup.getId(), new String(msg.getBytes("UTF-8")));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			ChattingRecordFile.saveChattingRecodToFile(chat, skyId);
			if (type.equals("0")) {
				if(chat_type == 0)
					tpChat.tp_chat_send_im(alias, skyId, msg);
				else if(chat_type == 5)
					tpChat.tp_conference_send_im(alias, skyId, msg);
			} else {
				sendMediaFile(msg, chat);
			}
		}
		LogManager.LogShow("ChatConversationActivity", "send msg end", LogManager.INFO);
	}

	// 发送多媒体文件
	private void sendMediaFile(String filename, final ChattingRecord chat){
		
		int sendSkyid 	= 0;
		int sendGid	 	= 0;
		int filetype	= -1;
		if(chat_type == 5){
			filetype	= TpFile.FILE_TRANS_TYPE_GROUP;
			sendGid 	= skyId;
		}else{
			filetype	= TpFile.FILE_TRANS_TYPE_NORMAL;
			sendSkyid 	= skyId;
		}
		LogManager.LogShow("ChatConversationActivity", "send file sendSkyid:"+sendSkyid+ "    sendGid:"+sendGid, LogManager.INFO);
		chat.isDownd 	= true;
		chat.tpFile 	= new TpFile();
		chat.tpFile.tp_file_upload(filename, filetype, sendSkyid, sendGid, new DataCallBack() {

			@Override
			public void Callback(int result, RspData resultdata, Object obj) {
				// TODO Auto-generated method stub
				LogManager.LogShow("ChatConversationActivity", "tp_file_upload  Callback result= " + result + " progress:"+chat.progress);
				if (result == TpFile.FILE_SERVER_UP_PROGRESS) {
					TpFileData pFile	= (TpFileData)obj;
					if(pFile == null) return;
					int progress 		= (pFile.getFileOffset()* 100)/pFile.getFileSize();
					chat.progress 		= progress;
					LogManager.LogShow("ChatConversationActivity", "tp_file_upload  progress:"+chat.progress);
					if(chat.progress <= 100){
						if(chat.progress == 100)
							chat.isDownd = false;
						handler.sendEmptyMessage(SETADAPTER);
					}
				}else{ //上传失败
					chat.isDownd = false;
					chat.tpFile.tp_file_upload_stop();
					handler.sendEmptyMessage(SETADAPTER);
				}
				
			}
		});
	}

	private void hideSearchLayout() {
		layout_bar_search.setVisibility(View.GONE);
		layout_bar.setVisibility(View.VISIBLE);
		listView.setVisibility(View.VISIBLE);
		layout_search.setVisibility(View.GONE);
	}

	/**
	 * 创建新的会话
	 */
	private void layout_ok() {
		final List<TPBuddyinfo> buddyinfoList = searchAdapter.selectedList;
		final int countB = buddyinfoList.size();
		String str = "";
		for (int i = 0; i < countB; i++) {
			TPBuddyinfo tinfo = buddyinfoList.get(i);
			str += BuddyInfoUtil.getAlias(tinfo);
			if (countB - 1 != i)
				str += ",";
		}
		if (countB > 1) { // 群会话
			tpChat.tp_conference_create(str, new DataCallBack() {

				@Override
				public void Callback(int result, RspData resultdata, Object obj) {
					LogManager.LogShow("ChatConversationActivity", "create conference result：" + result);
					if (result == TpChat.CHAT_CREATECONFERENCE_OK) {
						String str="";
						tpGroup = (TpGroup) obj;
						chat_type = 5;
						for (int i = 0; i < countB; i++) {
							LogManager.LogShow("ChatConversationActivity", "create conference ...：" + tpGroup.getId());
							TPBuddyinfo tinfo = buddyinfoList.get(i);
							str += BuddyInfoUtil.getAlias(tinfo)+ ",";
							tpChat.tp_conference_add_buddy(BuddyInfoUtil.getAlias(tinfo), tinfo.getSkyid(), tpGroup.getId());
						}
						tpGroup.setName(str);
					} else if (result == TpChat.CHAT_CREATECONFERENCE_ERR) {
						// handler.sendEmptyMessage(TpChat.CHAT_CREATECONFERENCE_ERR);
					} else if (result == TpChat.CHAT_CONFERENCE_CREATE_TIMEOUT) {
						// handler.sendEmptyMessage(TpChat.CHAT_CONFERENCE_CREATE_TIMEOUT);
					}
					handler.sendEmptyMessage(result);
				}
			});
		} else if (countB == 1) {
			TPBuddyinfo tinfo 	= buddyinfoList.get(0);
			skyId 				= tinfo.getSkyid();
			skyName 			= str;
//			icon 				= tinfo.getIcon();
			chat_type 			= 0;
			userName_tv.setText(skyName);
			searchListView.setVisibility(View.GONE);
			layout_r1.setVisibility(View.VISIBLE);
		}
		searchList.clear();
	}

	/*********************** very imagebutton onclick event handle end *********************************/

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		LogManager.LogShow("ChatConversationActivtity", "onActivityResult resultCode:" + resultCode, LogManager.DEBUG );
		if(resultCode != RESULT_OK)
			return;
		String type		= "";
		String filepath	= "";
		if(requestCode == TAKEPHOTO){
			type 		= "1";
			filepath	= strImgPath;
		}else if(requestCode == CHOOSE_PHOTO || requestCode == CHOOSE_VIDEO){
			if(data == null)return;
			Uri uri = data.getData();
			ContentResolver cr 	= getContentResolver();
			Cursor cursor 		= cr.query(uri, null, null, null, null);
			while(cursor.moveToNext()){
				filepath = cursor.getString(1);
//					Log.i("====_id", cursor.getString(0)+ "");
//					Log.i("====_path", cursor.getString(1)+ "");
//					Log.i("====_size", cursor.getString(2)+ "");
//					Log.i("====_display_name", cursor.getString(3)+ "");
			}
			type 				= MediaFile.fileType(filepath);
			if(type == null || type.equals("3")) return;
			
		}else if(requestCode == TAKEVIDEO){
			Uri uriVideo = data.getData();  
            Cursor cursor=this.getContentResolver().query(uriVideo, null, null, null, null);  
            if (cursor.moveToNext()) {  
                 /** _data：文件的绝对路径 ，_display_name：文件名 */  
            	filepath = cursor.getString(cursor.getColumnIndex("_data"));  
            }
            type = "2";
		}
		LogManager.LogShow("ChatConversationActivtity", "send file url333:" + filepath, LogManager.DEBUG);
		if (filepath.subSequence(0, 7).equals("file://"))
			filepath = filepath.substring(7);
		LogManager.LogShow("ChatConversationActivtity", "send file url:" + filepath + "  type:" + type, LogManager.DEBUG);
		sendMsg(type, filepath);
	}

	
	 /** 
     * 照相功能 
     */  
    private void cameraMethod() {  
            Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
            strImgPath	= "";
            strImgPath 	= Globals.FILE_PATH_IMAGE;//存放照片的文件夹  
            String fileName  	= System.currentTimeMillis() + ".jpg";//照片命名  
            File out = new File(strImgPath);  
            if (!out.exists()) {  
                 out.mkdirs();  
            }  
            out = new File(Globals.FILE_PATH_IMAGE, fileName);  
            strImgPath = strImgPath + fileName;//该照片的绝对路径  
            Uri uri = Uri.fromFile(out);  
            imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);  
            imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);  
            startActivityForResult(imageCaptureIntent, TAKEPHOTO);  

    }  
	
    /** 
     * 拍摄视频 
     */  
    private void videoMethod() {  
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);  
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);  
        startActivityForResult(intent, TAKEVIDEO);  
    }  
    

	/**
	 * 录音监听
	 * 
	 * @author Administrator
	 * 
	 */
	class AudioOnTouchListener implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				LogManager.LogShow("ChatConversationActivity", "action down", LogManager.VERBOSE);
				startAudio();
				break;

			case MotionEvent.ACTION_UP:
				LogManager.LogShow("ChatConversationActivity", "action up", LogManager.VERBOSE);
				stopAudio();
				break;
			}
			return false;
		}

	}

	// 开始录音
	private void startAudio() {
		btn_audio_talk.setText(getString(R.string.release_to_send));
		if (audioShowDialog == null)
			audioShowDialog = new AudioShowDialog(this, this.findViewById(R.id.rootView));
		audioShowDialog.showDialog();
	}

	// 结束录音
	private void stopAudio() {
		btn_audio_talk.setText(getString(R.string.hold_to_talk));
		String filePath = audioShowDialog.filePath;
		LogManager.LogShow("ChatConversationActivity", "audio url:" + filePath, LogManager.VERBOSE);
		audioShowDialog.dismissDialog();
		if (audioShowDialog.totalTime < 1) {
			showToast(getString(R.string.audio_too_short));
			FileUtil.delete(filePath);
		} else {
			if (filePath == null)
				return;
			sendMsg("3", filePath);
		}
	}


	private void appendTopic(String content) {
		content = "(" + content + ")";
		SpannableString ss = FileUtil.strToImage(content, ChatConversationActivity.this);
		int cursor = editText_msg.getSelectionStart();
		editText_msg.getText().insert(cursor, ss);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK)
			goBack();
		return super.onKeyDown(keyCode, event);
	}

	private void goBack() {
		if (from.equals("community")) {
			tpChatRoom.tp_chatroom_req_removechatroom(BuddyInfoUtil.getAlias(Globals.myInfo), Globals.skyid, tpGroup.getId()); // 退出聊天室
		}else if(chatList.size() > 0){
			ChatListDb dbChat	= new ChatListDb(this);
			Chat chat 			= dbChat.query(skyId);
			if(chat == null){
				chat 		= new Chat(chat_type, skyId, skyName);
				dbChat.add(chat);
				return;
			}
			if(chat.getCount() == 0)
				return;
			chat.setCount(0);
			dbChat.update(chat);
		}
	}

	@Override
	protected void onStart() {
		PlayTalkService.getInstance().setHandler(handler);
		PlayTalkService.getInstance().setValues(tpGroup, skyId);
		super.onStart();
	}

	@Override
	protected void onStop() {
		PlayTalkService.getInstance().setValues(null, -2);
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		notificationThread = null;
		searchList = null;
		super.onDestroy();
	}

	public void dispalynotifacation() {
		notification_tv.setText(notificationValue);
		notificationCount = 0;
		if (!isActiveThread) {
			notificationThread.start();
			isActiveThread = true;
		}
		if (notification_layout.getVisibility() == View.GONE) {
			notification_layout.setAnimation(AnimationUtils.loadAnimation(this, R.anim.push_hide));
			notification_layout.setVisibility(View.VISIBLE);
		}
	}

	private void hideNotificatoin() {
		notification_tv.setText("");
		notification_layout.setVisibility(View.GONE);
		notificationThread.stop();
	}

	private void initNotificationThread() {
		notificationThread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					while (true) {
						Thread.sleep(notificatoinDur);
						notificationCount++;
						if (notificationCount == 5) {
							handler.sendEmptyMessage(HIDENOTIFICATION);
						}
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}

	class MyTextWatcher implements TextWatcher {

		@Override
		public void afterTextChanged(Editable s) {

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if (fList == null)
				return;
			searchList.clear();
			int countF = fList.size();
			for (int i = 0; i < countF; i++) {
				TPBuddyinfo tpinfo = fList.get(i);
				if (BuddyInfoUtil.getAlias(tpinfo).toLowerCase() .indexOf(s.toString().trim().toLowerCase()) != -1) {
					searchList.add(tpinfo);
				}
			}
			handler.sendEmptyMessage(SEARCH_SETADAPTER);
		}

	}

}
